package cn.yiya.shiji.receiver;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat.Builder;
import android.text.TextUtils;
import android.util.Log;

import com.igexin.sdk.PushManager;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import cn.yiya.shiji.R;
import cn.yiya.shiji.activity.HomeIssueActivity;
import cn.yiya.shiji.activity.SplashActivity;
import cn.yiya.shiji.activity.WebViewActivity;
import cn.yiya.shiji.business.GeTui;
import cn.yiya.shiji.config.BaseApplication;
import cn.yiya.shiji.config.Configration;
import cn.yiya.shiji.config.CustomEvent;
import cn.yiya.shiji.config.UMengEvent;
import cn.yiya.shiji.entity.NotifyItem;
import cn.yiya.shiji.utils.Util;
import cn.yiya.shiji.views.ProgressDialog;

public class PushService extends Service {
	private int emotinoType = 0;
	private String urlMessage = "";
	private String url = "";
	private String notifyMsg;
	private int cmd = 0;
	private JSONObject options;
	private String flashId;

	private int Notification_ID_BASE = 110;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
        flags = START_STICKY;
		if(intent != null ){
			String content = intent.getStringExtra("content");
			if(!TextUtils.isEmpty(content)){
				parserJosn(content);
			}
		}
		
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		//初始化个推sdk
		PushManager.getInstance().initialize(this.getApplicationContext());
		GeTui.initGeTui(getApplicationContext());
		Log.e("个推","初始化个推");
	}

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @SuppressLint("InlinedApi")
	private void sendNotification(){
		if(!BaseApplication.canNotify){
			return;
		}
		String str = "";
		NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
		Builder builder = new Builder(this);
		switch(cmd){
		case 1:
			str = "宝妈通知您应该去完成今天的任务了！";
			break;
		case 2:
			str = "宝爸完成了今天的任务！";
			break;
		case 3:
			str = "您收到一个"+getEmotionStr(emotinoType)+"表情！";
			break;
		case 101:
			str = urlMessage;
			break;
		case 104:
			str = notifyMsg;
			builder.setContentText("您订阅的" + str + "闪购活动已经开始");
			break;
		default:
			str = notifyMsg;
			break;
		}

		PendingIntent contentIntent = getPendingIntent();//PendingIntent.getActivity(this, 100,  i,  PendingIntent.FLAG_UPDATE_CURRENT);
		if(contentIntent!=null){
			builder.setContentIntent(contentIntent);
		}

		builder.setAutoCancel(true);
		Bitmap btm = BitmapFactory.decodeResource(getResources(),
				R.mipmap.ic_launcher);
		builder.setLargeIcon(btm);
		builder.setSmallIcon(R.mipmap.ic_launcher);
		builder.setContentTitle("柿集");

		builder.setPriority(Notification.PRIORITY_DEFAULT);
		builder.setTicker("New message");
		if(BaseApplication.canVibrite){
			builder.setVibrate(new long[]{1000, 500, 1000, 500});
		}
		builder.setWhen(System.currentTimeMillis());
		Notification nf= builder.build();

		nm.notify("柿集", Notification_ID_BASE, nf);
	}

	private void parserJosn(String json){
		try {
			JSONObject jObj = new JSONObject(json);
			cmd = jObj.getInt("cmd");
			notifyMsg = jObj.getString("msg");
			options = jObj.getJSONObject("options");
			NotifyItem nItem = new NotifyItem();
			nItem.setTitle(notifyMsg);
			nItem.setTime(System.currentTimeMillis());
			nItem.setType(cmd);

			if(cmd==1){
				return;
			}else if(cmd==2){	//宝爸完成了任务
			}else if(cmd==3){	//显示表情
//				emotinoType = options.getInt("type");
				nItem.setTitle("你收到了一个"+getEmotionStr(emotinoType)+"表情！");
				nItem.setSubType(emotinoType);
//				nItem.save();
			}else if(cmd==101){
//				urlMessage = options.getString("msg");
//				url = options.getString("url");
				nItem.setTitle(urlMessage);
				nItem.setDescribe(url);

//				nItem.save();
				sendNotification();
				return;
			}else if(cmd==104){
				//判断app在后台的话弹下拉菜单，在前台弹选择对话框
				flashId = options.getString("flash_id");

				if(!Util.isBackground(getApplicationContext())){

					ProgressDialog.showCommonFlashSaleDialogCancel(BaseApplication.getInstance(), "您订阅的" + notifyMsg + "闪购活动已经开始", "暂不", "前往", new ProgressDialog.DialogClick() {
						@Override
						public void OkClick() {
							Intent intent = new Intent(getApplicationContext(), HomeIssueActivity.class);
							intent.putExtra("type", Configration.FLASH_SALE);
							intent.putExtra("flashId", flashId);
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
							startActivity(intent);
						}

						@Override
						public void CancelClick() {

						}
					});
				}else {
					sendNotification();

				}
				return;
			}else{
				sendNotification();
				return;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	private PendingIntent getPendingIntent(){
		Intent intent = null;
		PendingIntent pd = null;
        MobclickAgent.onEvent(getApplicationContext(), UMengEvent.ClickNotification);
		CustomEvent.onEvent(getApplicationContext(), ((BaseApplication)getApplication()).getDefaultTracker(), "PushService", CustomEvent.ClickNotification);
		switch(cmd){
		case 1:
			intent = new Intent(this, SplashActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			pd = PendingIntent.getActivity(this, 101, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			//PendingIntent.
			break;
		case 2:
			break;
		case 3:
			break;
		case 101:
			intent = new Intent(getApplicationContext(), WebViewActivity.class);
			intent.putExtra("url", url);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			pd = PendingIntent.getActivity(this, 100,  intent,  PendingIntent.FLAG_UPDATE_CURRENT);
			break;
		case 104:
			if(BaseApplication.isInit == false){
				intent = new Intent(getApplicationContext(), SplashActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.putExtra("main_activity_dest", "flash");
				intent.putExtra("flashId",flashId);
			}else {
				intent = new Intent(getApplicationContext(), HomeIssueActivity.class);
				intent.putExtra("type", Configration.FLASH_SALE);
				intent.putExtra("flashId",flashId);
			}

			pd = PendingIntent.getActivity(this, 103, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			break;
		default:
			intent = getPackageManager().getLaunchIntentForPackage("cn.yiya.shiji");
			pd = PendingIntent.getActivity(this, 99,  intent,  PendingIntent.FLAG_UPDATE_CURRENT);
			break;
		}
		
		return pd;
	}
	
	public String getEmotionStr(int emotionType){
		String emotionStr="";
		switch(emotionType){
		case 1:
			emotionStr = "早安";
			break;
		case 2:
			emotionStr = "抱抱";
			break;
		case 3:
			emotionStr = "谢谢";
			break;
		case 4:
			emotionStr = "I Love You";
			break;
		case 5:
			emotionStr = "Miss You";
			break;
		case 6:
			emotionStr = "晚安";
			break;
		default:
			break;
		}
		
		return emotionStr;
	}
}
